#!/usr/local/bin/perl
use LWP::Simple;
use Data::Dumper;
use Getopt::Std;
use strict;

my %opt;
getopts('vl:L:', \%opt);

open(F, "/usr/ports/INDEX-7") || die $!;
while(<F>)
{
  chomp;
  my @F = split('\|');
  my ($pkgname, $path, $prefix, $comment, $pkg_descr, $maintainer, $categories, $bdep, $rdep, $www) = @F;
  next if $www !~ m{cpan.org};
  print "$path non-dist CPAN page\n" if $www !~ m{dist};
  next if $www !~ m{dist};
  my ($name, $portver) = ($1, $2) if $pkgname =~ m{^(.+)(?:-|_)v?(\d\S+)$};
  die $pkgname if !$portver;
  my $html = get($www);
  next if $html =~ m{cannot be found};
  my $cpanver = $1 if $html =~ m{.*(?:This|Latest) Release.*?<td class=cell>(?:<a[^>]+>)?\S*?(?:-|_)v?(\d[\w\.]*)(?:</a>)?</td>}s;
  next if !$cpanver;
  my $note = 'Comparison failed';
  my $sign = '!';
  my $portver2 = normalize($portver);
  my $cpanver2 = normalize($cpanver);
  if ($portver2 eq $cpanver2) {
    $sign = '=';
    $note = 'up-to-date';
  }
  if ($portver2 lt $cpanver2) {
    $sign = '<';
    $note = "needs updating (CPAN has $cpanver)";
  }
  if ($portver2 gt $cpanver2) {
    $sign = '>';
    $note = "succeeds CPAN (CPAN has $cpanver)";
  }
  next if $opt{'L'} && $sign eq $opt{'L'};
  next if $opt{'l'} && $sign ne $opt{'l'};
  $sign .= '*' if -d "/var/db/pkg/$pkgname";
  printf("%-36s%-4s%-s\n", $opt{'v'} ? $pkgname : $name, $sign, $opt{'v'} ? $note : "");
}
close(F);

sub normalize
{
  my $ver = shift;
  $ver =~ s/,\d+$//g;
  $ver =~ s/_\d+$//g;
  $ver =~ s/\.//g;
  $ver =~ s/0+$//g;
  return $ver;
}
